package com.twotwoshop.service.search.strategy.SearchImpl;



import com.twotwoshop.service.search.config.SearchTypeConfig;
import com.twotwoshop.service.search.strategy.SearchGranter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 将策略整合起来 方便管理
 */
@Component
public class GoodsSearchFactory implements ApplicationContextAware {

    //根据type 获取 策略的hashmap
    private static Map<String, SearchGranter> granterPool = new ConcurrentHashMap<String, SearchGranter>();

    @Autowired
    private SearchTypeConfig searchTypeConfig;


    /**
     * 从配置文件中 获取策略
     * {
     *   es全局检索
     *   es: EsGranter
     *
     *   redis热点数据检索
     *   redis: RedisGranter
     * }
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, String> types = searchTypeConfig.getTypes();
        types.forEach((key, className) -> {
            // 根据配置中的类名获取Bean
            SearchGranter granter = (SearchGranter) applicationContext.getBean(className);
            // 将策略放入池中
            granterPool.put(key, granter);
        });
    }


    /**
     * 对外提供获取具体策略
     *
     * @param grantType 用户的搜索方式
     * @return
     */
    public SearchGranter gerGranter(String grantType) {

        //获取策略
        SearchGranter userGranter = granterPool.get(grantType);

        //返回策略
        return userGranter;
    }


}
